<template>
  <div class="supplier-classification-container">
    <div class="page-header">
      <h2 class="page-title">供应商分级分类管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddCategory">
          <el-icon><Plus /></el-icon>新增分类
        </el-button>
        <el-button type="success" @click="handleAddLevel">
          <el-icon><Plus /></el-icon>新增等级
        </el-button>
        <el-button type="primary" plain @click="handleImport">
          <el-icon><Upload /></el-icon>导入
        </el-button>
        <el-button type="primary" plain @click="handleExport">
          <el-icon><Download /></el-icon>导出
        </el-button>
      </div>
    </div>
    
    <el-card class="main-card">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="供应商分类管理" name="category">
          <div class="filter-container">
            <el-form :inline="true" :model="categoryQueryForm" class="filter-form">
              <el-form-item label="分类名称">
                <el-input v-model="categoryQueryForm.name" placeholder="请输入分类名称" clearable />
              </el-form-item>
              <el-form-item label="分类编码">
                <el-input v-model="categoryQueryForm.code" placeholder="请输入分类编码" clearable />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="categoryQueryForm.status" placeholder="请选择状态" clearable>
                  <el-option label="启用" value="active" />
                  <el-option label="禁用" value="inactive" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchCategories">
                  <el-icon><Search /></el-icon>查询
                </el-button>
                <el-button @click="resetCategoryForm">
                  <el-icon><Refresh /></el-icon>重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <el-table
            :data="categoryList"
            border
            stripe
            style="width: 100%"
            v-loading="categoryLoading"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="分类名称" />
            <el-table-column prop="code" label="分类编码" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="supplierCount" label="供应商数量" width="120" align="center" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                  {{ row.status === 'active' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEditCategory(row)">
                  <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button 
                  type="primary" 
                  link 
                  @click="handleToggleCategoryStatus(row)"
                >
                  <el-icon><VideoPlay v-if="row.status === 'inactive'" /><VideoPause v-else /></el-icon>
                  {{ row.status === 'active' ? '禁用' : '启用' }}
                </el-button>
                <el-button type="danger" link @click="handleDeleteCategory(row)">
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="categoryPagination.currentPage"
              v-model:page-size="categoryPagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="categoryPagination.total"
              @size-change="handleCategorySizeChange"
              @current-change="handleCategoryCurrentChange"
            />
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="供应商等级管理" name="level">
          <div class="filter-container">
            <el-form :inline="true" :model="levelQueryForm" class="filter-form">
              <el-form-item label="等级名称">
                <el-input v-model="levelQueryForm.name" placeholder="请输入等级名称" clearable />
              </el-form-item>
              <el-form-item label="等级编码">
                <el-input v-model="levelQueryForm.code" placeholder="请输入等级编码" clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchLevels">
                  <el-icon><Search /></el-icon>查询
                </el-button>
                <el-button @click="resetLevelForm">
                  <el-icon><Refresh /></el-icon>重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <el-table
            :data="levelList"
            border
            stripe
            style="width: 100%"
            v-loading="levelLoading"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="等级名称" />
            <el-table-column prop="code" label="等级编码" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="priority" label="优先级" width="100" align="center" />
            <el-table-column prop="supplierCount" label="供应商数量" width="120" align="center" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEditLevel(row)">
                  <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button type="danger" link @click="handleDeleteLevel(row)">
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="levelPagination.currentPage"
              v-model:page-size="levelPagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="levelPagination.total"
              @size-change="handleLevelSizeChange"
              @current-change="handleLevelCurrentChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 分类表单对话框 -->
    <el-dialog
      v-model="categoryDialogVisible"
      :title="categoryForm.id ? '编辑分类' : '新增分类'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类编码" prop="code">
          <el-input v-model="categoryForm.code" placeholder="请输入分类编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            placeholder="请输入分类描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="categoryForm.status"
            :active-value="'active'"
            :inactive-value="'inactive'"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCategoryForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 等级表单对话框 -->
    <el-dialog
      v-model="levelDialogVisible"
      :title="levelForm.id ? '编辑等级' : '新增等级'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="levelFormRef"
        :model="levelForm"
        :rules="levelRules"
        label-width="100px"
      >
        <el-form-item label="等级名称" prop="name">
          <el-input v-model="levelForm.name" placeholder="请输入等级名称" />
        </el-form-item>
        <el-form-item label="等级编码" prop="code">
          <el-input v-model="levelForm.code" placeholder="请输入等级编码" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="levelForm.priority" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="levelForm.description"
            type="textarea"
            placeholder="请输入等级描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="levelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitLevelForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { 
  Plus, Edit, Delete, Search, Refresh, Upload, Download,
  VideoPlay, VideoPause
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 标签页状态
const activeTab = ref('category')

// 分类查询表单
const categoryQueryForm = reactive({
  name: '',
  code: '',
  status: ''
})

// 等级查询表单
const levelQueryForm = reactive({
  name: '',
  code: ''
})

// 分类表单
const categoryDialogVisible = ref(false)
const categoryForm = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  status: 'active'
})
const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类编码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9_-]+$/, message: '编码只能包含字母、数字、下划线和短横线', trigger: 'blur' }
  ]
}

// 等级表单
const levelDialogVisible = ref(false)
const levelForm = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  priority: 1
})
const levelRules = {
  name: [
    { required: true, message: '请输入等级名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入等级编码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9_-]+$/, message: '编码只能包含字母、数字、下划线和短横线', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请输入优先级', trigger: 'blur' }
  ]
}

// 分类数据
const categoryList = ref([
  {
    id: 1,
    name: '原材料供应商',
    code: 'RAW_MATERIAL',
    description: '提供生产所需原材料的供应商',
    supplierCount: 120,
    createTime: '2023-05-15 10:30:45',
    status: 'active'
  },
  {
    id: 2,
    name: '设备供应商',
    code: 'EQUIPMENT',
    description: '提供生产设备和机械的供应商',
    supplierCount: 45,
    createTime: '2023-05-16 14:20:30',
    status: 'active'
  },
  {
    id: 3,
    name: '服务供应商',
    code: 'SERVICE',
    description: '提供各类服务的供应商',
    supplierCount: 78,
    createTime: '2023-05-17 09:15:22',
    status: 'active'
  },
  {
    id: 4,
    name: '物流供应商',
    code: 'LOGISTICS',
    description: '提供物流和运输服务的供应商',
    supplierCount: 35,
    createTime: '2023-05-18 16:40:12',
    status: 'active'
  },
  {
    id: 5,
    name: '包装材料供应商',
    code: 'PACKAGING',
    description: '提供包装材料的供应商',
    supplierCount: 28,
    createTime: '2023-05-19 11:25:33',
    status: 'inactive'
  }
])
const categoryLoading = ref(false)
const categoryPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 5
})

// 等级数据
const levelList = ref([
  {
    id: 1,
    name: 'A级',
    code: 'LEVEL_A',
    description: '战略合作伙伴，长期稳定合作',
    priority: 1,
    supplierCount: 25,
    createTime: '2023-05-15 10:30:45'
  },
  {
    id: 2,
    name: 'B级',
    code: 'LEVEL_B',
    description: '重要供应商，合作关系良好',
    priority: 2,
    supplierCount: 48,
    createTime: '2023-05-16 14:20:30'
  },
  {
    id: 3,
    name: 'C级',
    code: 'LEVEL_C',
    description: '一般供应商，合作关系稳定',
    priority: 3,
    supplierCount: 86,
    createTime: '2023-05-17 09:15:22'
  },
  {
    id: 4,
    name: 'D级',
    code: 'LEVEL_D',
    description: '临时供应商，合作关系待观察',
    priority: 4,
    supplierCount: 47,
    createTime: '2023-05-18 16:40:12'
  }
])
const levelLoading = ref(false)
const levelPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 4
})

// 表单引用
const categoryFormRef = ref()
const levelFormRef = ref()

// 处理标签页切换
const handleTabChange = () => {
  if (activeTab.value === 'category') {
    loadCategoryData()
  } else {
    loadLevelData()
  }
}

// 加载分类数据
const loadCategoryData = () => {
  categoryLoading.value = true
  // 模拟API调用
  setTimeout(() => {
    categoryLoading.value = false
  }, 500)
}

// 加载等级数据
const loadLevelData = () => {
  levelLoading.value = true
  // 模拟API调用
  setTimeout(() => {
    levelLoading.value = false
  }, 500)
}

// 查询分类
const searchCategories = () => {
  categoryPagination.currentPage = 1
  loadCategoryData()
}

// 重置分类查询表单
const resetCategoryForm = () => {
  categoryQueryForm.name = ''
  categoryQueryForm.code = ''
  categoryQueryForm.status = ''
  searchCategories()
}

// 查询等级
const searchLevels = () => {
  levelPagination.currentPage = 1
  loadLevelData()
}

// 重置等级查询表单
const resetLevelForm = () => {
  levelQueryForm.name = ''
  levelQueryForm.code = ''
  searchLevels()
}

// 处理分类分页大小变化
const handleCategorySizeChange = (val: number) => {
  categoryPagination.pageSize = val
  loadCategoryData()
}

// 处理分类当前页变化
const handleCategoryCurrentChange = (val: number) => {
  categoryPagination.currentPage = val
  loadCategoryData()
}

// 处理等级分页大小变化
const handleLevelSizeChange = (val: number) => {
  levelPagination.pageSize = val
  loadLevelData()
}

// 处理等级当前页变化
const handleLevelCurrentChange = (val: number) => {
  levelPagination.currentPage = val
  loadLevelData()
}

// 新增分类
const handleAddCategory = () => {
  categoryForm.id = ''
  categoryForm.name = ''
  categoryForm.code = ''
  categoryForm.description = ''
  categoryForm.status = 'active'
  categoryDialogVisible.value = true
}

// 编辑分类
const handleEditCategory = (row: any) => {
  categoryForm.id = row.id
  categoryForm.name = row.name
  categoryForm.code = row.code
  categoryForm.description = row.description
  categoryForm.status = row.status
  categoryDialogVisible.value = true
}

// 切换分类状态
const handleToggleCategoryStatus = (row: any) => {
  const action = row.status === 'active' ? '禁用' : '启用'
  ElMessageBox.confirm(`确定要${action}该分类吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API调用
    row.status = row.status === 'active' ? 'inactive' : 'active'
    ElMessage.success(`${action}成功`)
  }).catch(() => {})
}

// 删除分类
const handleDeleteCategory = (row: any) => {
  ElMessageBox.confirm(`确定要删除分类"${row.name}"吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API调用
    const index = categoryList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      categoryList.value.splice(index, 1)
      categoryPagination.total--
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

// 提交分类表单
const submitCategoryForm = () => {
  categoryFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 模拟API调用
      if (categoryForm.id) {
        // 编辑
        const index = categoryList.value.findIndex(item => item.id === categoryForm.id)
        if (index !== -1) {
          categoryList.value[index] = {
            ...categoryList.value[index],
            name: categoryForm.name,
            code: categoryForm.code,
            description: categoryForm.description,
            status: categoryForm.status
          }
          ElMessage.success('编辑成功')
        }
      } else {
        // 新增
        const newCategory = {
          id: Date.now(),
          name: categoryForm.name,
          code: categoryForm.code,
          description: categoryForm.description,
          status: categoryForm.status,
          supplierCount: 0,
          createTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
        }
        categoryList.value.unshift(newCategory)
        categoryPagination.total++
        ElMessage.success('添加成功')
      }
      categoryDialogVisible.value = false
    }
  })
}

// 新增等级
const handleAddLevel = () => {
  levelForm.id = ''
  levelForm.name = ''
  levelForm.code = ''
  levelForm.description = ''
  levelForm.priority = 1
  levelDialogVisible.value = true
}

// 编辑等级
const handleEditLevel = (row: any) => {
  levelForm.id = row.id
  levelForm.name = row.name
  levelForm.code = row.code
  levelForm.description = row.description
  levelForm.priority = row.priority
  levelDialogVisible.value = true
}

// 删除等级
const handleDeleteLevel = (row: any) => {
  ElMessageBox.confirm(`确定要删除等级"${row.name}"吗？此操作不可恢复！`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟API调用
    const index = levelList.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      levelList.value.splice(index, 1)
      levelPagination.total--
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

// 提交等级表单
const submitLevelForm = () => {
  levelFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 模拟API调用
      if (levelForm.id) {
        // 编辑
        const index = levelList.value.findIndex(item => item.id === levelForm.id)
        if (index !== -1) {
          levelList.value[index] = {
            ...levelList.value[index],
            name: levelForm.name,
            code: levelForm.code,
            description: levelForm.description,
            priority: levelForm.priority
          }
          ElMessage.success('编辑成功')
        }
      } else {
        // 新增
        const newLevel = {
          id: Date.now(),
          name: levelForm.name,
          code: levelForm.code,
          description: levelForm.description,
          priority: levelForm.priority,
          supplierCount: 0,
          createTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
        }
        levelList.value.push(newLevel)
        // 按优先级排序
        levelList.value.sort((a, b) => a.priority - b.priority)
        levelPagination.total++
        ElMessage.success('添加成功')
      }
      levelDialogVisible.value = false
    }
  })
}

// 导入
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 初始化
onMounted(() => {
  loadCategoryData()
})
</script>

<style scoped>
.supplier-classification-container {
  padding: var(--content-padding);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.main-card {
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 